import { ISearchBar } from '@ibiz/model-core';
import { PropType, defineComponent, h, ref } from 'vue';
import { useControlController, useNamespace } from '@ibiz-template/vue3-util';
import { IControlProvider, IModal } from '@ibiz-template/runtime';
import { EhrSearchBarController } from './ehr-search-bar.controller';
import { SearchBar } from './common/search-bar/search-bar';
import './ehr-search-bar.scss';

export const EhrSearchBarControl = defineComponent({
  name: 'IBizEhrSearchBarControl',
  props: {
    modelData: {
      type: Object as PropType<ISearchBar>,
      required: true,
    },
    context: { type: Object as PropType<IContext>, required: true },
    params: { type: Object as PropType<IParams>, default: () => ({}) },
    provider: { type: Object as PropType<IControlProvider> },
  },
  setup() {
    const c: EhrSearchBarController = useControlController(
      (...args) => new EhrSearchBarController(...args),
    );

    const ns = useNamespace('ehr-search-bar');

    const buttonRef = ref();

    const openSearchModal = async (event: MouseEvent) => {
      const overlay = ibiz.overlay.createPopover(
        (modal: IModal) => {
          return h(SearchBar, {
            controller: c,
            modal,
          });
        },
        {},
        {
          height: '80%',
          noArrow: true,
          autoClose: true,
          placement: 'top',
          width: `${buttonRef.value.ref.offsetWidth}px`,
        } as any,
      );
      overlay.present(event.target as HTMLElement);
      await overlay.onWillDismiss();
    };

    return {
      c,
      ns,
      buttonRef,
      openSearchModal,
    };
  },
  render() {
    return (
      <div class={this.ns.b()}>
        {this.c.model.searchBarStyle === 'SEARCHBAR2' ? (
          <el-button
            type='text'
            ref='buttonRef'
            class={this.ns.e('button')}
            onClick={this.openSearchModal}
          >
            <div class={this.ns.em('button', 'left')}>
              <ion-icon name='filter-circle'></ion-icon>
              {this.c.model.logicName}
            </div>
            <ion-icon
              name='caret-up'
              class={this.ns.em('button', 'right')}
            ></ion-icon>
          </el-button>
        ) : (
          <SearchBar controller={this.c} />
        )}
      </div>
    );
  },
});
